package org.jeecg.modules.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.SneakyThrows;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jeecg.common.util.MinioUtil;
import org.jeecg.modules.wdc.entity.CarDev;
import org.jeecg.modules.wdc.entity.CarDrivingrecord;
import org.jeecg.modules.wdc.service.ICarDevService;
import org.jeecg.modules.wdc.service.ICarDrivingrecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;
import java.net.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zhengch
 * @date 2021年09月17日 4:13 下午
 */

public class DahuaData implements  Runnable {


    private ICarDrivingrecordService carDrivingrecordService;

    private    String sheBeiId ;

    private final static String localPath = "/hrzh/wdcPhoto/";

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    // 大华查询接口地址
    private static final String daHuaUrl = "http://46.1.225.126:8080/dahuaIS/rest/picrecord/search";

    private CarDrivingrecord carDrivingrecord;
    // get 方法
    private HttpGet httpGet = HttpGetUtil.getInstance();
    //httpClien 客户端
    private CloseableHttpClient httpClient = HttpClients.createDefault();
    //  返回结果
    private CloseableHttpResponse response = null;

    //是否自定义时间

    private  Boolean isCustomTime;
    //自定义时间

    private  String customTime;



    public  DahuaData (String sheBeiId,ICarDrivingrecordService iCarDrivingrecordService,Boolean isCustomTime,String customTime){
       this.sheBeiId  =sheBeiId;
       this.carDrivingrecordService = iCarDrivingrecordService;
       this.isCustomTime = isCustomTime;
       this.customTime = customTime;
    }

    // 获取过车记录
//    public void getCarRecord() throws URISyntaxException, IOException, ParseException {
//        QueryWrapper<CarDev> wrapper = new QueryWrapper<>();
//        wrapper.lambda().like(CarDev::getDevchnid,"$");
//        List<CarDev> list = carDevService.list(wrapper);
//        for (CarDev carDev : list) {
//            execute.execute(new Runnable() {
//                @SneakyThrows
//                @Override
//                public void run() {
//                    doGet(carDev.getDevchnid());
//                }
//            });
//
//        }
//        System.out.println("-----------------大华采集接口运行完成----------");
//    }

    @SneakyThrows
    @Override
    public void run() {
     doGet(sheBeiId);
    }

    //执行get请求
    public void doGet(String sheBeiId) throws URISyntaxException, IOException, ParseException {
        System.out.println(Thread.currentThread().getName()+"线程--------------开始"+sheBeiId+"设备数据采集---------------");
        DahuaParams dahuaParams = new DahuaParams();
        page page = new page();
        dahuaParams.setStartDate(getYesterdayTime() + " " + "00:00:00");
        dahuaParams.setEndDate(getYesterdayTime() + " " + "23:59:59");
        dahuaParams.setDevChnId(sheBeiId);
        int pageNo = 0;
        //循环取每页数据，直至最后一页结束
        while (true) {
            pageNo += 1;
            System.out.println(Thread.currentThread().getName()+"线程: 现在是：" + pageNo + "页");
            page.setPageNo(String.valueOf(pageNo));
            dahuaParams.setPage(page);
            String param = JSON.toJSONString(dahuaParams);
            URI uri = new URIBuilder(daHuaUrl).setParameter("q", param).build();
            httpGet.setURI(uri);
            response = httpClient.execute(httpGet);
            String content = EntityUtils.toString(response.getEntity(), "UTF-8");
            JSONObject jsonObject = JSON.parseObject(content);
            JSONObject data = (JSONObject) jsonObject.get("data");
            JSONArray jsonArray = data.getJSONArray("rows");
            paresObjectAndSave(jsonArray);
            //行数小于20时，是最后一页 跳出循环
            if (jsonArray.size() < 20) {
                System.out.println(Thread.currentThread().getName() + ": 到最后一页");
                break;
            }

        }
    }

    //格式化数据存入数据库
    public void paresObjectAndSave(JSONArray jsonArray) throws ParseException {
        for (int i = 0; i < jsonArray.size(); i++) {
            //取得每条过车记录
            JSONObject record = (JSONObject) jsonArray.get(i);
            Date capDate = simpleDateFormat.parse(record.get("capDate").toString());
            String devChnId = record.get("devChnId").toString();
            String devChnName = record.get("devChnName").toString();
            carDrivingrecord = record.toJavaObject(CarDrivingrecord.class);
            carDrivingrecord.setId(null);
            carDrivingrecord.setCarCapdate(capDate);
            String carNum = carDrivingrecord.getCarNum();
            //车牌不是外省的；直接跳出;进行下一次循环。
            if (!checkCarNum(carNum)) {
                continue;
            }
            //判断车牌号是否符合规范
            if (!checkCarNumOk(carNum)) {
                continue;
            }
            //存储图片
            if (carDrivingrecord.getCarImgurl() == null || "".equals(carDrivingrecord.getCarImgurl())) {
                //当图片地址不存在时 直接跳出进行下一个
                continue;
            }
            try {
                String dateString = getYesterdayTime();
                //拼接图片与存储桶名称
                String bukateBame = dateString.replace("-", "");
                String fileName = "IMG_HTTP_" + bukateBame + "_" + getRandomNickname(10) + "_" + carDrivingrecord.getCarNum() + "_" + String.valueOf(carDrivingrecord.getCarCapdate().getTime()) + ".jpg";
                //图片下载到本地的地址
                String filePath = localPath + fileName;
                //先下载图片到本地
                downLoadImage(carDrivingrecord.getCarImgurl(), fileName);
                InputStream inputStream = getImageStream(filePath);
                String imgUrl = MinioUtil.uploadBucketName(inputStream, fileName, bukateBame);
                //删除本地图片
                delImage(filePath);
                carDrivingrecord.setCarImg1url(carDrivingrecord.getCarImgurl());
                carDrivingrecord.setCarImgurl(imgUrl);
                carDrivingrecord.setCarDevchnid(devChnId);
                carDrivingrecord.setCarDevchnname(devChnName);
            } catch (Exception e) {
                //有异常直接跳出
                e.printStackTrace();
                continue;
            }
            carDrivingrecordService.save(carDrivingrecord);
        }
    }

    //判断车牌是否为外省
    private boolean checkCarNum(String carNum) {
        if (carNum.contains("琼")) {
            return false;
        } else {
            return true;
        }
    }

    //判断车牌是否符合规范
    public boolean checkCarNumOk(String carNum) {
        Pattern pattern = Pattern.compile("^[\u4e00-\u9fa5|WJ]{1}[A-Z0-9]{6}$");
        Matcher matcher = pattern.matcher(carNum);
        if (!matcher.matches()) {
            //车牌号格式不对!!
            return false;
        } else {
            //车牌号格式正确!!
            return true;
        }

    }

    //获取图片输入流
    public InputStream getImageStream(String filepath) throws Exception {
        File file = new File(filepath);
        InputStream inputStream = new FileInputStream(file);
        return inputStream;
    }

    //删除本地图片
    public void delImage(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
          //  System.out.println(Thread.currentThread().getName()+": "+filePath + "删除成功");
        }
    }


    //获取昨天的年月日（字符串）
    private String getYesterdayTime() {
        if(isCustomTime == true){
            return  customTime;
        }
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        String yesterday = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        return yesterday;
    }

    /**
     * java生成随机数字10位数
     *
     * @param length 长度
     * @return
     */
    public static String getRandomNickname(int length) {
        String val = "";
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            val += String.valueOf(random.nextInt(10));
        }
        return val;
    }


    private void downLoadImage(String imgUrl, String fileName) throws Exception {
        //new一个URL对象
        URL url = new URL(imgUrl);
        //打开链接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置请求方式为"GET"
        conn.setRequestMethod("GET");
        //超时响应时间为5秒
        conn.setConnectTimeout(5 * 1000);
        //通过输入流获取图片数据
        InputStream inStream = conn.getInputStream();
        //得到图片的二进制数据，以二进制封装得到数据，具有通用性
        byte[] data = readInputStream(inStream);
        String filePath = localPath + fileName;
        //new一个文件对象用来保存图片，默认保存当前工程根目录
        File imageFile = new File(filePath);
        //创建输出流
        FileOutputStream outStream = new FileOutputStream(imageFile);
        //写入数据
        outStream.write(data);
        //关闭输出流
        outStream.close();
    }


    // 读取输入流
    private byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        //每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len = 0;
        //使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
        inStream.close();
        //把outStream里的数据写入内存
        return outStream.toByteArray();
    }


}
